package org.example.auth.service;

import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import org.example.auth.domain.ResourcesPO;
import org.example.auth.domain.RolePO;
import org.example.auth.repository.RoleRepository;
import org.example.common.contant.RedisConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 资源与角色匹配关系管理业务类
 *
 * @author lsliang
 */
@Service
@AllArgsConstructor
public class ResourceServiceImpl {

    private RedisTemplate<String,Object> redisTemplate;

    private RoleRepository roleRepository;

    @PostConstruct
    public void initData() {
        Map<String, List<String>> resourceRolesMap = Maps.newTreeMap();
        List<RolePO> roleList = roleRepository.findAll();
        if (CollUtil.isNotEmpty(roleList)) {
            roleList.forEach(role -> {
                List<ResourcesPO> resourcesList = role.getResources();
                if (CollUtil.isNotEmpty(resourcesList)) {
                    resourcesList.forEach(resources -> {
                        String resourceName = resources.getService() + resources.getName();
                        List<String> authorities = resourceRolesMap.get(resourceName);
                        if (CollUtil.isEmpty(authorities)) {
                            authorities = Lists.newArrayList();
                        }
                        authorities.add(role.getName());
                        resourceRolesMap.put(resourceName, authorities);
                    });
                }
            });
        }
        redisTemplate.opsForHash().putAll(RedisConstant.RESOURCE_ROLES_MAP, resourceRolesMap);
    }
}
